package com.yl.chainStore.control.user

import com.baomidou.mybatisplus.core.toolkit.IdWorker
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.control.BaseCtrl
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.common.util.permissionsViewListToTreeSelect
import com.yl.users.entity.CompanyRole
import com.yl.users.pojo.vo.CompanyRoleSelectVo
import com.yl.users.services.ICompanyRoleService
import com.yl.users.services.ICompanyUserService
import com.yl.users.services.ISysCompanyService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*

/**
 * 公司角色管理
 */
@RestController
@RequestMapping("company/user/role")
open class CompanyRoleController(
	private val iCompanyRoleService: ICompanyRoleService,
	private val iCompanyUserService: ICompanyUserService,
	private val iSysCompanyService: ISysCompanyService
) : BaseCtrl() {

	/**
	 * 获取分页数据
	 */
	@PostMapping("rolePage")
	@PermsCode("system:user:role:list")
	@Transactional
	open fun rolePage(@RequestBody body: CompanyRoleSelectVo): ResponseBody {

		val page = Page<CompanyRole>(body.current, body.size)
		return returnSuccess(iSysCompanyService.getCompanyRolePage(page, body))
	}

	/**
	 * 获取角色明细
	 */
	@GetMapping("roleDetail/{id}")
//	@PermsCode("system:user:role:view")
	@Transactional
	open fun roleDetail(@PathVariable id: Long): ResponseBody {
		val adminRole = iCompanyRoleService.getCompanyRole(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		val permViewIds = iCompanyRoleService.getRolePermIds(adminRole.id)
		val roleFieldTree = iCompanyRoleService.getRoleFieldIds(adminRole.id)
		adminRole.fieldIds = roleFieldTree
		adminRole.permissionsIds = permViewIds
		return returnSuccess(adminRole)
	}

	/**
	 * 保存角色
	 */
	@PostMapping("save")
	@PermsCode("system:user:role:save")
	@Transactional(rollbackFor = [Exception::class])
	open fun save(@RequestBody role: CompanyRole): ResponseBody {
		role.roleCode = IdWorker.get32UUID()
		role.roleType = 1
		role.companyId = getContext().companyId
		if (role.id == 0L) {
			val addRole = iSysCompanyService.addCompanyRole(role)
			if (addRole.code != ErrorCode.SUCCESS.code) {
				return addRole
			}
		} else {
			val updateRole = iCompanyRoleService.update(role)
			if (updateRole.code != ErrorCode.SUCCESS.code) {
				return updateRole
			}
		}
		if (role.permissionsIds != null && role.permissionsIds!!.isNotEmpty()) {
			val bindUser = iCompanyRoleService.reBindRolePermissions(role.id, role.permissionsIds!!)
			if (bindUser.code != ErrorCode.SUCCESS.code) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return bindUser
			}
		}
		if (role.fieldIds != null && role.fieldIds!!.isNotEmpty()) {
			iCompanyRoleService.reBindRoleField(role.fieldIds!!, role.id)
		}
		iCompanyUserService.cleanCacheByCompany(role.companyId)
		return returnSuccess()
	}

	/**
	 * 删除角色
	 */
	@PostMapping("del/{id}")
	@PermsCode("system:user:role:del")
	@Transactional
	open fun del(@PathVariable id: Long): ResponseBody {
		val companyRole = iCompanyRoleService.getCompanyRole(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if (companyRole.companyId != getContext().companyId) {
			return returnError(ErrorCode.DATA_DELETE_FAILED, "没有权限删除")
		}
		if (companyRole.roleCode.equals("admin")) {
			return returnError(ErrorCode.DATA_DELETE_FAILED, "不能删除管理员角色")
		}
		iCompanyRoleService.delRole(id)
		iCompanyUserService.cleanCacheByCompany(companyRole.companyId)
		return returnSuccess()
	}

	/**
	 * 获取权限树
	 */
	@GetMapping("getPermTree")
	@Transactional
	open fun getPermTree(): ResponseBody {
		val companyPermViewList = iSysCompanyService.getCompanyPermViewList(getContext().companyId)
		return returnSuccess(permissionsViewListToTreeSelect(companyPermViewList, 0L))
	}

	/**
	 * 获取字段树
	 */
	@GetMapping("getFieldTree")
	@Transactional
	open fun getFieldTree(): ResponseBody {
		return returnSuccess(iSysCompanyService.getCompanyFieldTree(getContext().companyId))
	}

	/**
	 * 获取角色列表(其他地方用)
	 */
	@GetMapping("getRoleList")
	@Transactional
	open fun getRoleList(): ResponseBody {
		val companyRoleList =
			iSysCompanyService.getCompanyRoleList(CompanyRoleSelectVo(companyId = getContext().companyId))
		val resList = mutableListOf<Map<String,Any>>()
		for(role in companyRoleList){
			val map = mutableMapOf<String,Any>()
			map["id"] = role.id
			map["name"] = role.roleName
			resList.add(map)
		}
		return returnSuccess(resList)
	}
}
